// https://leetcode.cn/problems/longest-palindromic-subsequence/description/

// 算法思路总结：
// 1. 使用动态规划求解最长回文子序列
// 2. dp[i][j]表示s[i..j]的最长回文子序列长度
// 3. 当s[i]==s[j]时，长度等于中间子序列加2
// 4. 当s[i]!=s[j]时，取左右子序列的最大值
// 5. 时间复杂度：O(n²)，空间复杂度：O(n²)

#include <iostream>
using namespace std;

#include <string>
#include <vector>
#include <algorithm> 

class Solution 
{
public:
    int longestPalindromeSubseq(string s) 
    {
        int m = s.size();

        vector<vector<int>> dp(m, vector<int>(m, 2));

        for (int i = m - 1 ; i >= 0 ; i--)
        {
            for (int j = i ; j < m ; j++)
            {
                if (s[i] == s[j])
                {
                    if (i == j)
                        dp[i][j] = 1;
                    else if (i + 1 == j)
                        dp[i][j] = 2;
                    else dp[i][j] = dp[i + 1][j - 1] + 2;
                }
                else
                    dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
            }
        }
        return dp[0][m - 1];
    }
};

int main()
{
    string s1 = "bbbab", s2 = "cbbd";
    Solution sol;

    cout << sol.longestPalindromeSubseq(s1) << endl;
    cout << sol.longestPalindromeSubseq(s2) << endl;

    return 0;
}